<template>
  <div>
    <Header/>
    <div class="userInfo">
      <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
        <el-tab-pane label="个人信息" name="first">
          <div class="info">
            <el-form :model="userInfo" :rules="rules" ref="ruleForm" label-width="80px" class="demo-ruleForm">
              <el-form-item label="头像" prop="avatar">
                <el-upload class="avatar-uploader" action="http://localhost:9999/upload" :show-file-list="false"
                           :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                  <img v-if="userInfo.avatar" :src="userInfo.avatar" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </el-form-item>
              <el-form-item label="姓名" prop="username">
                <el-input v-model="userInfo.username" style="width:230px"></el-input>
              </el-form-item>
              <el-form-item label="生日" prop="birthday">
                <el-date-picker v-model="userInfo.birthday" style="width:230px" type="date" placeholder="选择日期">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="性别" prop="gender">
                <el-radio-group v-model="userInfo.gender">
                  <el-radio label="0">男</el-radio>
                  <el-radio label="1">女</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="电话" prop="phone">
                <el-input v-model="userInfo.phone" style="width:230px"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button size="small" type="primary" @click="save('ruleForm')">保存</el-button>
                <!-- <el-button @click="reset">重置</el-button> -->
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>
        <el-tab-pane label="修改密码" name="second">
          <div class="password">
            <el-form :model="passWord" :rules="passRules" ref="passWord" label-width="80px" class="demo-ruleForm">
              <el-form-item label="旧密码" prop="oldPass">
                <el-input placeholder="请输入旧密码" v-model="passWord.oldPass" style="width:230px" show-password></el-input>
              </el-form-item>
              <el-form-item label="新密码" prop="newPass">
                <el-input placeholder="请输入新密码" v-model="passWord.newPass" style="width:230px" show-password></el-input>
              </el-form-item>
              <el-form-item label="确认密码" prop="newPass2">
                <el-input placeholder="请再次输入新密码" v-model="passWord.newPass2" style="width:230px"
                          show-password></el-input>
              </el-form-item>
              <el-form-item>
                <el-button size="small" type="primary" @click="submit('passWord')">提交</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>
        <el-tab-pane label="收货地址" name="third">
          <div class="address">
            <el-button type="primary" size="small" style="margin-bottom:10px" @click="addAddressBtn">新增地址</el-button>
            <el-row :gutter="20">
              <el-col :span="8" v-for="item in addressList" :key="item.id">
                <el-card shadow="hover" :style="{'color':item.defaultValue?'#67c23a':''}">
                  <div>姓名：{{ item.receiverName }}</div>
                  <div>电话：{{ item.phone }}</div>
                  <div :title="item.urbanAddr+item.detailAddr ">地址：{{ item.urbanAddr }}{{ item.detailAddr }}</div>
                  <div>
                    默认地址：
                    <el-switch @change="setDefaultAddress(item)" v-model="item.defaultValue" active-color="#13ce66"
                               inactive-color="#ff4949">
                    </el-switch>
                    <div style="text-align:center;float:right">
                      <el-button type="text" size="small" icon="el-icon-edit" @click="editAddress(item)">修改</el-button>
                      <el-button style="color:#f56c6c" type="text" size="small" icon="el-icon-delete"
                                 @click="deleteAddress(item.id)">删除
                      </el-button>
                    </div>
                  </div>

                </el-card>
              </el-col>
            </el-row>
          </div>
        </el-tab-pane>
      </el-tabs>
      <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" width="500px">
        <el-form :model="addressInfo" :rules="addressRules" ref="addressRef" label-width="110px">
          <el-form-item prop="receiverName" label="收件人姓名">
            <el-input v-model="addressInfo.receiverName" style="width:260px"></el-input>
          </el-form-item>
          <el-form-item prop="phone" label="收件人电话">
            <el-input v-model="addressInfo.phone" style="width:260px"></el-input>
          </el-form-item>
          <el-form-item prop="urbanAddr" label="省市区地址">
            <el-input v-model="addressInfo.urbanAddr" style="width:260px"></el-input>
          </el-form-item>
          <el-form-item prop="detailAddr" label="详细地址">
            <el-input v-model="addressInfo.detailAddr" style="width:260px"></el-input>
          </el-form-item>

        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button @click="resetForm('addressRef')">取 消</el-button>
          <el-button type="primary" @click="submitForm('addressRef')">确 定</el-button>
        </div>
      </el-dialog>

    </div>
    <Footer/>
  </div>
</template>

<script>
import {put, get, post, del} from "@/utils/request";
import Header from "@/views/Components/Header/index.vue";
import Footer from "@/views/Components/Footer/index.vue";
import {removeToken} from "@/utils/auth";

export default {
  components: {
    Header,
    Footer,
  },
  data() {
    var validateOldPass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入旧密码"));
      } else {
        callback();
      }
    };
    var validateNewPass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入新密码"));
      } else {
        if (this.passWord.newPass2 !== "") {
          this.$refs.passWord.validateField("newPass2");
        }
        callback();
      }
    };
    var validateNewPass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.passWord.newPass) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      activeName: "first",
      circleUrl:
          "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png",

      userInfo: {
        avatar: "",
        username: "",
        birthday: "",
        gender: "",
        phone: "",
        id: "",
      },
      rules: {},
      passWord: {
        oldPass: "",
        newPass: "",
        newPass2: "",
      },
      passRules: {
        oldPass: [
          {
            required: true,
            trigger: "blur",
            validator: validateOldPass,
          },
        ],
        newPass: [
          {
            required: true,
            trigger: "blur",
            validator: validateNewPass,
          },
        ],
        newPass2: [
          {
            required: true,
            trigger: "blur",
            validator: validateNewPass2,
          },
        ],
      },
      addressList: [],
      dialogFormVisible: false,
      addressInfo: {
        receiverName: "",
        phone: "",
        detailAddr: "",
        urbanAddr: "",
      },
      addressRules: {
        receiverName: [
          {
            required: true,
            message: "收件人姓名不能为空",
            trigger: "blur",
          },
        ],
        phone: [
          {
            required: true,
            message: "收件人电话不能为空",
            trigger: "blur",
          },
        ],
        detailAddr: [
          {
            required: true,
            message: "不能为空",
            trigger: "blur",
          },
        ],
        urbanAddr: [
          {
            required: true,
            message: "不能为空",
            trigger: "blur",
          },
        ],
      },
      dialogTitle: "新增地址",
      isAdd: false,
      // proviceList: provice,
    };
  },

  created() {
    this.userInfo = this.$store.state.userInfo;
    this.getAddressList();
  },
  methods: {
    handleClick(tab) {
      if (tab.name === "third") {
        this.getAddressList();
      }
    },
    // 头像上传成功后
    handleAvatarSuccess(res, file) {
      this.userInfo.avatar = res.data;
    },
    // 头像上传成功之前
    beforeAvatarUpload(file) {
      const whiteList = [
        "image/webp",
        "image/jpeg",
        "image/jpg",
        "image/png",
      ];
      if (whiteList.indexOf(file.type) === -1) {
        this.$message.error("上传头像图片格式不正确!");
      }
      // const isLt2M = file.size / 1024 / 1024 < 2;
      // if (!isLt2M) {
      //     this.$message.error("上传头像图片大小不能超过 2MB!");
      // }
      // return whiteList && isLt2M;
      return whiteList;
    },
    // 修改个人信息保存按钮
    save(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let param = {
            avatar: this.userInfo.avatar,
            birthday: this.$moment(this.userInfo.birthday).format(
                "YYYY-MM-DD"
            ),
            gender: this.userInfo.gender,
            id: this.userInfo.id,
            phone: this.userInfo.phone,
            username: this.userInfo.username,
          };
          put("/user/updateUser", param).then((res) => {
            if (res && res.data) {
              // 返回的数据就是最新的个人信息
              this.userInfo = res.data;
              this.$notify({
                title: "成功",
                message: "信息保存成功",
                type: "success",
              });
            }
          });
        } else {
          this.$notify.error({
            title: "错误",
            message: "保存失败",
          });
          return false;
        }
      });
    },
    submit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          put("/user/updatePassword", {
            newPassword: this.passWord.newPass,
            oldPassword: this.passWord.oldPass,
          }).then((res) => {
            if (res && res.message === "ok") {
              this.$notify({
                title: "成功",
                message: "密码修改成功！",
                type: "success",
              });
              // 退出登录
              removeToken();
              this.$router.push("/login")
            }
          });
        } else {
          this.$notify.error({
            title: "错误",
            message: "密码修改失败！",
          });
          return false;
        }
      });
    },

    // 获取用户的所有收货地址
    getAddressList() {
      this.addressList = [];
      get("/address").then((res) => {
        if (res && res.data) {
          this.addressList = res.data;
        }
      });
    },
    // 设置、取消  为默认地址
    setDefaultAddress(val) {
      if (val.defaultValue) {
        put(`/address/setDefault/${val.id}`)
            .then((res) => {
              if (res && res.message === "ok") {
                this.$notify({
                  title: "成功",
                  message: "已设置为默认地址",
                  type: "success",
                });
                this.getAddressList();
              }
            })
            .catch((err) => {
              this.$notify.error({
                title: "错误",
                message: "设置为默认地址失败！",
              });
            });
      } else {
        put(`/address/cancelDefault/${val.id}`)
            .then((res) => {
              if (res && res.message === "ok") {
                this.$notify({
                  title: "成功",
                  message: "已取消为默认地址",
                  type: "success",
                });
                this.getAddressList();
              }
            })
            .catch((err) => {
              this.$notify.error({
                title: "错误",
                message: "取消为默认地址失败！",
              });
            });
      }
    },

    handleChange(value) {
      console.log("value", value);
    },
    // 点击新增按钮
    addAddressBtn() {
      this.dialogFormVisible = true;
      this.isAdd = true;
      this.dialogTitle = "新增地址";
    },
    // 取消 新增地址
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.dialogFormVisible = false;
    },
    // 保存 新增地址
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.isAdd) {
            // 新增
            post("/address", {
              detailAddr: this.addressInfo.detailAddr,
              phone: this.addressInfo.phone,
              receiverName: this.addressInfo.receiverName,
              urbanAddr: this.addressInfo.urbanAddr,
              userId: this.userInfo.id,
            }).then((res) => {
              if (res && res.message == "ok") {
                this.$notify({
                  title: "成功",
                  message: "新增地址成功！",
                  type: "success",
                });
                this.dialogFormVisible = false;
                this.getAddressList();
              }
            });
          } else {
            // 修改
            put("/address", {
              detailAddr: this.addressInfo.detailAddr,
              phone: this.addressInfo.phone,
              receiverName: this.addressInfo.receiverName,
              urbanAddr: this.addressInfo.urbanAddr,
              id: this.addressInfo.id,
            }).then((res) => {
              if (res && res.message == "ok") {
                this.$notify({
                  title: "成功",
                  message: "修改地址成功！",
                  type: "success",
                });
                this.dialogFormVisible = false;
                this.getAddressList();
              }
            });
          }
        } else {
          this.$notify.error({
            title: "错误",
            message: "保存地址失败！",
          });
          return false;
        }
      });
    },
    // 修改 地址
    editAddress(row) {
      this.dialogFormVisible = true;
      this.dialogTitle = "修改地址";
      this.isAdd = false;
      this.addressInfo = row;
    },
    // 删除地址
    deleteAddress(id) {
      this.$confirm("此操作将永久删除该条地址, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
          .then(() => {
            del("/address", {id}).then((res) => {
              if (res && res.message == "ok") {
                this.$notify({
                  title: "成功",
                  message: "地址删除成功！",
                  type: "success",
                });
                this.getAddressList();
              }
            });
          })
          .catch(() => {
            this.$notify.error({
              title: "错误",
              message: "地址删除失败",
            });
          });
    },
  },
};
</script>
<style lang="scss" scoped>
.userInfo {
  width: 70%;
  min-height: calc(100vh - 300px);
  margin: 0 auto;
  padding: 20px;

  .info {
    // background-color: #ddd;
    padding: 0 10px 0 0;

    .avatar-uploader .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }

    .avatar-uploader .el-upload:hover {
      border-color: #409eff;
    }

    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }

    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
  }

  .password {
    padding: 20px 0;
  }

  .address {
    .el-card {
      height: 200px;
      margin-bottom: 20px;

      div {
        line-height: 30px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }
}
</style>
